﻿Imports DotNetNuke
Imports DotNetNuke.Entities.Modules
Imports System.Collections.Generic
Imports Telerik.Web.UI
Imports DotNetNuke.Entities.Tabs
Imports DotNetNuke.Security.Permissions


Imports System
Imports System.Data
Imports System.Linq

Imports DotNetNuke.Entities.Portals
Imports System.Xml
Imports DotNetNuke.Security.Roles
Imports System.Threading
Imports DotNetNuke.Entities.Content
Imports DotNetNuke.Entities.Content.Taxonomy

Imports System.Collections
Imports System.ComponentModel
Imports System.ComponentModel.Design
Imports System.Web.UI
Imports System.Web.UI.Design
Imports System.Web.UI.WebControls
Imports System.Diagnostics
Imports DotNetNuke.UI.Utilities
Imports DotNetNuke.UI.WebControls
Imports DotNetNuke.UI.Skins



Namespace dnnWerk.Modules.Admin.Pages

    Public Enum Position
        Child
        Below
        Above
    End Enum

    Partial Class View
        Inherits PortalModuleBase

#Region "Properties"

        Protected ReadOnly Property Tabs() As List(Of TabInfo)
            Get
                If rblMode.SelectedValue = "H" Then
                    Return TabController.GetPortalTabs(Null.NullInteger, Null.NullInteger, False, True, False, True)
                Else
                    Return TabController.GetPortalTabs(PortalId, Null.NullInteger, False, True, False, True)
                End If
            End Get
        End Property

        Private ReadOnly Property Icon_Everyone() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Everyone.png"
            End Get
        End Property

        Private ReadOnly Property Icon_RegisteredUsers() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_User.png"
            End Get
        End Property

        Private ReadOnly Property Icon_Secured() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_UserSecure.png"
            End Get
        End Property

        Private ReadOnly Property Icon_AdminOnly() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_UserAdmin.png"
            End Get
        End Property

        Private ReadOnly Property IconPageDisabled() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Disabled.png"
            End Get
        End Property

        Private ReadOnly Property IconPageHidden() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Hidden.png"
            End Get
        End Property

        Private ReadOnly Property IconPortal() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Portal.png"
            End Get
        End Property

        Private ReadOnly Property IconUp() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Up.png"
            End Get
        End Property

        Private ReadOnly Property IconDown() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Down.png"
            End Get
        End Property

        Private ReadOnly Property IconHome() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Home.png"
            End Get
        End Property

        Private ReadOnly Property IconEdit() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Edit.png"
            End Get
        End Property

        Private ReadOnly Property IconAdd() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Add.png"
            End Get
        End Property

        Private ReadOnly Property IconDelete() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_Delete.png"
            End Get
        End Property

        Private ReadOnly Property IconView() As String
            Get
                Return Me.TemplateSourceDirectory & "/images/Icon_View.png"
            End Get
        End Property

#End Region

#Region "Event Handlers"

        Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init

            DotNetNuke.Framework.AJAX.RegisterScriptManager()

            UI.Utilities.ClientAPI.RegisterClientReference(Me.Page, ClientAPI.ClientNamespaceReferences.dnn_dom)
            RegisterClientScriptBlock(Me.Page, "dnn.controls.js")
            RegisterClientScriptBlock(Me.Page, "dnn.controls.dnnmultistatebox.js")

        End Sub

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

            Try

                CheckSecurity()
                pnlHost.Visible = UserInfo.IsSuperUser

                ' If this is the first visit to the page, bind the tab data to the page listbox
                If Page.IsPostBack = False Then

                    'ctlSkin.SkinRoot = DotNetNuke.UI.Skins.SkinController.RootSkin
                    'ctlContainer.SkinRoot = DotNetNuke.UI.Skins.SkinController.RootContainer

                    LocalizeControl()

                    If Not String.IsNullOrEmpty(Request.QueryString("isHost")) Then
                        If Boolean.Parse(Request.QueryString("isHost")) Then
                            rblMode.SelectedValue = "H"
                        End If
                    End If

                    BindTree()

                End If


                'ctlPages.ContextMenus(0).Items(2).Attributes.Add("onclick", "return confirm('Are you sure?');")

            Catch exc As Exception    'Module failed to load
                ProcessModuleLoadException(Me, exc)
            End Try


        End Sub

        Protected Sub cmdCopySkin_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdCopySkin.Click
            Try
                TabController.CopyDesignToChildren(New TabController().GetTab(Convert.ToInt32(ctlPages.SelectedNode.Value), PortalId, False), drpSkin.SelectedValue, drpContainer.SelectedValue)
                UI.Skins.Skin.AddModuleMessage(Me, Services.Localization.Localization.GetString("DesignCopied", Me.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.GreenSuccess)
            Catch ex As Exception
                UI.Skins.Skin.AddModuleMessage(Me, Services.Localization.Localization.GetString("DesignCopyError", Me.LocalResourceFile), UI.Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
                ProcessModuleLoadException(Me, ex)
            End Try
        End Sub

        Protected Sub rblMode_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles rblMode.SelectedIndexChanged
            BindTree()
        End Sub

        Protected Sub ctlPages_NodeClick(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadTreeNodeEventArgs) Handles ctlPages.NodeClick
            Dim tabid As Integer = Convert.ToInt32(e.Node.Value)
            BindTab(tabid)
            pnlDetails.Visible = True
            pnlBulk.Visible = False
            grdModules.Rebind()
        End Sub

        Protected Sub ctlPages_ContextMenuItemClick(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadTreeViewContextMenuEventArgs) Handles ctlPages.ContextMenuItemClick

            Session("SelectedNode") = e.Node.Value

            Dim objTabController As New TabController
            Dim objTab As TabInfo = objTabController.GetTab(Integer.Parse(e.Node.Value), PortalId, False)

            Select Case e.MenuItem.Value.ToLower
                'Case "bulkcreate"

                '    pnlBulk.Visible = True
                '    btnBulkCreate.CommandArgument = e.Node.Value
                '    ctlPages.FindNodeByValue(e.Node.Value).Selected = True
                '    txtBulk.Focus()
                Case "makehome"
                    Dim ctrl As New PortalController
                    Dim PortalInfo As PortalInfo = ctrl.GetPortal(PortalId, LocaleController.Instance.GetCurrentLocale(PortalId).Code)
                    If Not PortalInfo Is Nothing Then
                        PortalInfo.HomeTabId = objTab.TabID
                        ctrl.UpdatePortalInfo(PortalInfo)
                        DotNetNuke.Common.Utilities.DataCache.ClearPortalCache(PortalId, True)
                        Response.Redirect(NavigateURL(TabId))
                    End If
                    BindTree()
                Case "view"
                    Response.Redirect(objTab.FullUrl)
                Case "edit"
                    Response.Redirect(NavigateURL(objTab.TabID, "Tab", "action=edit", "returntabid=" & TabId.ToString), True)
                Case "delete"
                    TabController.DeleteTab(objTab.TabID, PortalSettings, UserId)
                    BindTree()
                Case "moveup"
                    objTabController.MoveTab(objTab, TabMoveType.Up)
                    BindTree()
                Case "movedown"
                    objTabController.MoveTab(objTab, TabMoveType.Down)
                    BindTree()
                Case "add"
                    pnlBulk.Visible = True
                    btnBulkCreate.CommandArgument = e.Node.Value
                    ctlPages.FindNodeByValue(e.Node.Value).Selected = True
                    txtBulk.Focus()
                    pnlDetails.Visible = False
                    'Response.Redirect(NavigateURL(objTab.TabID, "Tab", "action=add", "returntabid=" & TabId.ToString), True)
                Case "hide"
                    objTab.IsVisible = False
                    objTabController.UpdateTab(objTab)
                    BindTree()
                Case "show"
                    objTab.IsVisible = True
                    objTabController.UpdateTab(objTab)
                    BindTree()
                Case "disable"
                    objTab.DisableLink = True
                    objTabController.UpdateTab(objTab)
                    BindTree()
                Case "enable"
                    objTab.DisableLink = False
                    objTabController.UpdateTab(objTab)
                    BindTree()
            End Select

        End Sub

        Protected Sub ctlPages_NodeDrop(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadTreeNodeDragDropEventArgs) Handles ctlPages.NodeDrop

            Dim sourceNode As RadTreeNode = e.SourceDragNode
            Dim destNode As RadTreeNode = e.DestDragNode
            Dim dropPosition As RadTreeViewDropPosition = e.DropPosition
            If Not destNode Is Nothing Then

                If sourceNode.TreeView.SelectedNodes.Count <= 1 Then
                    PerformDragAndDrop(dropPosition, sourceNode, destNode)
                ElseIf sourceNode.TreeView.SelectedNodes.Count > 1 Then
                    For Each node As RadTreeNode In sourceNode.TreeView.SelectedNodes
                        PerformDragAndDrop(dropPosition, node, destNode)
                    Next
                End If

                destNode.Expanded = True

                For Each node As RadTreeNode In ctlPages.GetAllNodes
                    If node.Value = e.SourceDragNode.Value Then
                        node.Selected = True
                    Else
                        node.Selected = False
                    End If
                Next

            End If

        End Sub

        Protected Sub ctlPages_NodeEdit(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadTreeNodeEditEventArgs) Handles ctlPages.NodeEdit

            Dim objTabController As New TabController
            Dim objTab As TabInfo = objTabController.GetTab(Integer.Parse(e.Node.Value), PortalId, False)

            'Check for invalid 
            If Regex.IsMatch(e.Text, "^AUX$|^CON$|^LPT[1-9]$|^CON$|^COM[1-9]$|^NUL$|^SITEMAP$|^LINKCLICK$|^KEEPALIVE$|^DEFAULT$|^ERRORPAGE$", RegexOptions.IgnoreCase) Then
                Dim strInvalid As String = String.Format(Localization.GetString("InvalidTabName", Me.LocalResourceFile), e.Text)
                e.Node.Text = objTab.TabName
                e.Text = objTab.TabName
                ctlAjax.ResponseScripts.Add("alert('" & strInvalid & "');return false;")
            Else
                objTab.TabName = e.Text
                objTabController.UpdateTab(objTab)
            End If

            BindTree()

        End Sub

        Protected Sub btnTreeCommand_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnTreeCommand.Click
            Dim btn As ImageButton = CType(sender, ImageButton)
            If btn.CommandName.ToLower = "expand" Then
                ctlPages.ExpandAllNodes()
                btn.CommandName = "Collapse"
                btnTreeCommand.ImageUrl = Me.TemplateSourceDirectory & "/images/Icon_Collapse.png"
                btnTreeCommand.ToolTip = Localization.GetString("Collapse", Me.LocalResourceFile)
            Else
                ctlPages.CollapseAllNodes()
                ctlPages.Nodes(0).Expanded = True
                btn.CommandName = "Expand"
                btnTreeCommand.ImageUrl = Me.TemplateSourceDirectory & "/images/Icon_Expand.png"
                btnTreeCommand.ToolTip = Localization.GetString("Expand", Me.LocalResourceFile)
            End If
        End Sub

        Protected Sub grdModules_NeedDataSource(ByVal source As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles grdModules.NeedDataSource


            Dim lst As New List(Of ModuleInfo)

            If Not ctlPages.SelectedNode Is Nothing Then

                Dim dic As New Dictionary(Of Integer, ModuleInfo)
                Dim tabid As Integer = Convert.ToInt32(ctlPages.SelectedNode.Value)
                Dim ModuleController As New ModuleController
                dic = ModuleController.GetTabModules(tabid)

                For Each objModule As ModuleInfo In dic.Values
                    If objModule.IsDeleted = False Then
                        lst.Add(objModule)
                    End If
                Next

            End If

            grdModules.DataSource = lst

        End Sub

        Protected Sub ctlAjax_AjaxRequest(ByVal sender As Object, ByVal e As Telerik.Web.UI.AjaxRequestEventArgs) Handles ctlAjax.AjaxRequest
            Dim cmd As String = e.Argument.Split(Char.Parse("|"))(0)
            Dim arg As String = e.Argument.Split(Char.Parse("|"))(1)

            Select Case cmd.ToLower
                Case "getmenuitems"
                    Dim objTabController As New TabController
                    Dim objTab As TabInfo = objTabController.GetTab(Integer.Parse(arg), PortalId, False)
                    If Not objTab Is Nothing Then

                        Dim ctl As RadContextMenu = CType(ctlPages.FindControl("ctlContext"), RadContextMenu)
                        If Not ctl Is Nothing Then
                            ctl.Items(1).Visible = False
                        End If

                    End If
            End Select

        End Sub

        Protected Sub ctlPages_NodeExpand(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadTreeNodeEventArgs) Handles ctlPages.NodeExpand
            AddChildnodes(e.Node)
        End Sub

        Protected Sub btnBulkCreate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBulkCreate.Click

            Dim strValue As String = txtBulk.Text
            strValue = strValue.Replace(vbCr, vbLf)
            strValue = strValue.Replace(vbCrLf, vbLf)
            strValue = strValue.Replace(vbLf & vbLf, vbLf).Trim

            If strValue.Length = 0 Then
                Exit Sub
            End If

            Dim strPages As String() = strValue.Split(Char.Parse(vbLf))
            Dim parentId As Integer = Convert.ToInt32(CType(sender, Button).CommandArgument)
            Dim ctrl As New TabController
            Dim objRoot As TabInfo = ctrl.GetTab(parentId, PortalId, True)
            Dim lstTabs As New List(Of TabInfo)

            For Each strLine As String In strPages
                Dim oTab As New TabInfo
                oTab.TabName = strLine
                If strLine.StartsWith(">") Then
                    oTab.Level = strLine.LastIndexOf(">") + 1
                Else
                    oTab.Level = 0
                End If
                lstTabs.Add(oTab)
            Next

            Dim currentIndex As Integer = -1
            For Each oTab As TabInfo In lstTabs

                currentIndex += 1

                If oTab.TabName.StartsWith(">") = False Then
                    If parentId = Null.NullInteger Then
                        oTab.TabID = CreateRootTab(oTab.TabName)
                        objRoot = ctrl.GetTab(oTab.TabID, PortalId, True)
                    Else
                        oTab.TabID = CreateTabFromParent(objRoot, oTab.TabName, parentId)
                    End If
                Else
                    oTab.TabID = CreateTabFromParent(objRoot, oTab.TabName.Replace(">", ""), GetParentTabId(lstTabs, currentIndex, oTab.Level - 1))
                End If

            Next

            BindTree()

            Dim tabid As Integer = Convert.ToInt32(lstTabs(0).TabID)
            ctlPages.FindNodeByValue(tabid.ToString).Selected = True
            ctlPages.FindNodeByValue(tabid.ToString).ExpandParentNodes()

            BindTab(tabid)
            pnlDetails.Visible = True
            pnlBulk.Visible = False
            grdModules.Rebind()

        End Sub

        Public Sub cmdDeleteModule_Click(ByVal sender As Object, ByVal e As System.EventArgs)

            Dim intModule As Integer = Convert.ToInt32(CType(sender, ImageButton).CommandArgument)
            Dim intTab As Integer = Convert.ToInt32(ctlPages.SelectedNode.Value)

            Dim ctrl As New ModuleController
            ctrl.DeleteTabModule(intTab, intModule, True)
            ctrl.ClearCache(intTab)

            grdModules.Rebind()

        End Sub

        Protected Sub cmdUpdate_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmdUpdate.Click

            Dim intTab As Integer = Convert.ToInt32(ctlPages.SelectedNode.Value)
            Dim objTabcontroller As New TabController
            Dim objTab As TabInfo = objTabcontroller.GetTab(intTab, PortalId, True)
            If Not objTab Is Nothing Then

                objTab.TabName = txtName.Text
                objTab.Title = txtTitle.Text
                objTab.Description = txtDescription.Text
                objTab.KeyWords = txtKeywords.Text
                objTab.IsVisible = chkVisible.Checked
                objTab.DisableLink = chkDisabled.Checked

                objTab.IsDeleted = False
                objTab.Url = ctlURL.Url

                objTab.SkinSrc = drpSkin.SelectedValue
                objTab.ContainerSrc = drpContainer.SelectedValue
                objTab.TabPath = GenerateTabPath(objTab.ParentId, objTab.TabName)

                objTab.TabPermissions.Clear()
                If objTab.PortalID <> Null.NullInteger Then
                    objTab.TabPermissions.AddRange(dgPermissions.Permissions)
                End If

                If objTab.TabName = "" Then
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, Localization.GetString("InvalidTabName", Me.LocalResourceFile), Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
                    Exit Sub
                End If

                'Check for invalid 
                If Regex.IsMatch(objTab.TabName, "^AUX$|^CON$|^LPT[1-9]$|^CON$|^COM[1-9]$|^NUL$|^SITEMAP$|^LINKCLICK$|^KEEPALIVE$|^DEFAULT$|^ERRORPAGE$", RegexOptions.IgnoreCase) Then
                    DotNetNuke.UI.Skins.Skin.AddModuleMessage(Me, Localization.GetString("InvalidTabName", Me.LocalResourceFile), Skins.Controls.ModuleMessage.ModuleMessageType.RedError)
                    Exit Sub
                End If


                If txtRefresh.Text.Length > 0 AndAlso IsNumeric(txtRefresh.Text) Then
                    objTab.RefreshInterval = Convert.ToInt32(txtRefresh.Text)
                End If

                objTab.SiteMapPriority = Single.Parse(txtSitemapPriority.Text)
                objTab.PageHeadText = txtMeta.Text
                objTab.IsSecure = chkSecure.Checked
                objTab.PermanentRedirect = chkPermanentRedirect.Checked

                Dim strIcon As String = ""
                Dim strIconLarge As String = ""
                strIcon = ctlIcon.Url
                strIconLarge = ctlIconLarge.Url

                objTab.IconFile = strIcon
                objTab.IconFileLarge = strIconLarge


                objTab.Terms.Clear()
                objTab.Terms.AddRange(termsSelector.Terms)

                objTabcontroller.UpdateTab(objTab)

                BindTree()

            End If

        End Sub

#End Region

#Region "Private Methods"

        Private Sub BindTab(ByVal TabId As Integer)

            Dim ctrl As New TabController
            Dim objTab As TabInfo = ctrl.GetTab(TabId, PortalId, True)

            If Not objTab Is Nothing Then


                Session("SelectedNode") = TabId.ToString

                'Bind TabPermissionsGrid to TabId 
                dgPermissions.TabID = objTab.TabID
                dgPermissions.DataBind()

                cmdMore.NavigateUrl = NavigateURL(TabId, "", "ctl=Tab", "action=edit", "returntabid=" & Me.TabId.ToString)
                'cmdMore.Target = "_blank"

                txtTitle.Text = objTab.Title
                txtName.Text = objTab.TabName
                chkVisible.Checked = objTab.IsVisible

                txtSitemapPriority.Text = objTab.SiteMapPriority.ToString
                txtDescription.Text = objTab.Description
                txtKeywords.Text = objTab.KeyWords
                txtMeta.Text = objTab.PageHeadText
                txtRefresh.Text = objTab.RefreshInterval


                If objTab.SkinSrc <> "" Then
                    Select Case objTab.SkinSrc.Substring(0, 3)
                        Case "[L]"
                            rblSkinMode.SelectedValue = "S"
                        Case "[G]"
                            rblSkinMode.SelectedValue = "H"
                    End Select
                End If
                BindSkins()

                Try
                    drpSkin.SelectedValue = objTab.SkinSrc
                Catch
                End Try

                If objTab.ContainerSrc <> "" Then
                    Select Case objTab.ContainerSrc.Substring(0, 3)
                        Case "[L]"
                            rblContainerMode.SelectedValue = "S"
                        Case "[G]"
                            rblContainerMode.SelectedValue = "H"
                    End Select
                End If
                BindContainers()

                Try
                    drpContainer.SelectedValue = objTab.ContainerSrc
                Catch
                End Try

                If objTab.Url = "" Then
                    ctlURL.UrlType = "N"
                Else
                    ctlURL.Url = objTab.Url
                End If

                chkPermanentRedirect.Checked = objTab.PermanentRedirect
                txtKeywords.Text = objTab.KeyWords
                txtDescription.Text = objTab.Description

                chkDisabled.Checked = objTab.DisableLink
                If objTab.TabID = PortalSettings.AdminTabId OrElse objTab.TabID = PortalSettings.SplashTabId OrElse _
                    objTab.TabID = PortalSettings.HomeTabId OrElse objTab.TabID = PortalSettings.LoginTabId OrElse _
                    objTab.TabID = PortalSettings.UserTabId OrElse objTab.TabID = PortalSettings.SuperTabId Then
                    chkDisabled.Enabled = False
                End If

                If PortalSettings.SSLEnabled Then
                    chkSecure.Enabled = True
                    chkSecure.Checked = objTab.IsSecure
                Else
                    chkSecure.Enabled = False
                    chkSecure.Checked = objTab.IsSecure
                End If

                ctlIcon.Url = objTab.IconFile
                ctlIconLarge.Url = objTab.IconFileLarge

                termsSelector.PortalId = objTab.PortalID
                termsSelector.Terms = objTab.Terms
                termsSelector.DataBind()

            End If

        End Sub

        Private Sub BindSkins()

            drpSkin.Items.Clear()

            Dim objPortals As New PortalController
            Dim objPortal As PortalInfo = objPortals.GetPortal(PortalSettings.PortalId)

            If rblSkinMode.SelectedValue = "H" Then
                For Each Skin As KeyValuePair(Of String, String) In SkinController.GetSkins(objPortal, SkinController.RootSkin, SkinScope.Host)
                    drpSkin.Items.Add(New RadComboBoxItem(Skin.Key, Skin.Value))
                Next
            Else
                For Each Skin As KeyValuePair(Of String, String) In SkinController.GetSkins(objPortal, SkinController.RootSkin, SkinScope.Site)
                    drpSkin.Items.Add(New RadComboBoxItem(Skin.Key, Skin.Value))
                Next
            End If

            drpSkin.Items.Insert(0, New RadComboBoxItem(Localization.GetString("DefaultSkin", LocalResourceFile), ""))

        End Sub

        Private Sub BindContainers()

            drpContainer.Items.Clear()

            Dim objPortals As New PortalController
            Dim objPortal As PortalInfo = objPortals.GetPortal(PortalSettings.PortalId)

            If rblContainerMode.SelectedValue = "H" Then
                For Each Container As KeyValuePair(Of String, String) In SkinController.GetSkins(objPortal, SkinController.RootContainer, SkinScope.Host)
                    drpContainer.Items.Add(New RadComboBoxItem(Container.Key, Container.Value))
                Next
            Else
                For Each Container As KeyValuePair(Of String, String) In SkinController.GetSkins(objPortal, SkinController.RootContainer, SkinScope.Site)
                    drpContainer.Items.Add(New RadComboBoxItem(Container.Key, Container.Value))
                Next
            End If

            drpContainer.Items.Insert(0, New RadComboBoxItem(Localization.GetString("DefaultContainer", LocalResourceFile), ""))

        End Sub

        Private Sub CheckSecurity()
            If (Not TabPermissionController.HasTabPermission("CONTENT")) AndAlso Not ModulePermissionController.HasModulePermission(Me.ModuleConfiguration.ModulePermissions, "CONTENT, EDIT") Then
                Response.Redirect(NavigateURL("Access Denied"), True)
            End If
        End Sub

        Private Sub LocalizeControl()

            ctlIcon.ShowFiles = True
            ctlIcon.ShowImages = True
            ctlIcon.ShowTabs = False
            ctlIcon.ShowUrls = False
            ctlIcon.Required = False

            ctlIcon.ShowLog = False
            ctlIcon.ShowNewWindow = False
            ctlIcon.ShowTrack = False
            ctlIcon.FileFilter = glbImageFileTypes
            ctlIcon.Width = "275px"

            ctlIconLarge.ShowFiles = ctlIcon.ShowFiles
            ctlIconLarge.ShowImages = ctlIcon.ShowImages
            ctlIconLarge.ShowTabs = ctlIcon.ShowTabs
            ctlIconLarge.ShowUrls = ctlIcon.ShowUrls
            ctlIconLarge.Required = ctlIcon.Required

            ctlIconLarge.ShowLog = ctlIcon.ShowLog
            ctlIconLarge.ShowNewWindow = ctlIcon.ShowNewWindow
            ctlIconLarge.ShowTrack = ctlIcon.ShowTrack
            ctlIconLarge.FileFilter = ctlIcon.FileFilter
            ctlIconLarge.Width = ctlIcon.Width

            Me.ctlPages.ContextMenus(0).Items(0).Text = Localization.GetString("ViewPage", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(1).Text = Localization.GetString("EditPage", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(2).Text = Localization.GetString("DeletePage", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(3).Text = Localization.GetString("MovePageUp", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(4).Text = Localization.GetString("MovePageDown", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(5).Text = Localization.GetString("AddPage", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(6).Text = Localization.GetString("HidePage", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(7).Text = Localization.GetString("ShowPage", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(8).Text = Localization.GetString("EnablePage", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(9).Text = Localization.GetString("DisablePage", Me.LocalResourceFile)
            Me.ctlPages.ContextMenus(0).Items(10).Text = Localization.GetString("MakeHome", Me.LocalResourceFile)

            lblBulkIntro.Text = Localization.GetString("BulkCreateIntro", LocalResourceFile)
            btnBulkCreate.Text = Localization.GetString("btnBulkCreate", LocalResourceFile)

            ctlPages.ContextMenus(0).Items(0).ImageUrl = Me.IconView
            ctlPages.ContextMenus(0).Items(1).ImageUrl = Me.IconEdit
            ctlPages.ContextMenus(0).Items(2).ImageUrl = Me.IconDelete
            ctlPages.ContextMenus(0).Items(3).ImageUrl = Me.IconUp
            ctlPages.ContextMenus(0).Items(4).ImageUrl = Me.IconDown
            ctlPages.ContextMenus(0).Items(5).ImageUrl = Me.IconAdd
            ctlPages.ContextMenus(0).Items(6).ImageUrl = Me.IconPageHidden
            ctlPages.ContextMenus(0).Items(7).ImageUrl = Me.IconPageHidden
            ctlPages.ContextMenus(0).Items(8).ImageUrl = Me.IconPageDisabled
            ctlPages.ContextMenus(0).Items(9).ImageUrl = Me.IconPageDisabled
            ctlPages.ContextMenus(0).Items(10).ImageUrl = Me.IconHome


            rblMode.Items(0).Text = Localization.GetString("ShowPortalTabs", Me.LocalResourceFile)
            rblMode.Items(1).Text = Localization.GetString("ShowHostTabs", Me.LocalResourceFile)
            lblHead.Text = Localization.GetString("lblHead", Me.LocalResourceFile)

            lblDisabled.Text = Localization.GetString("lblDisabled", Me.LocalResourceFile)
            lblHidden.Text = Localization.GetString("lblHidden", Me.LocalResourceFile)
            lblHome.Text = Localization.GetString("lblHome", Me.LocalResourceFile)

            lblSecure.Text = Localization.GetString("lblSecure", Me.LocalResourceFile)
            lblEveryone.Text = Localization.GetString("lblEveryone", Me.LocalResourceFile)
            lblRegistered.Text = Localization.GetString("lblRegistered", Me.LocalResourceFile)
            lblAdminOnly.Text = Localization.GetString("lblAdminOnly", Me.LocalResourceFile)
            btnTreeCommand.ToolTip = Localization.GetString("Expand", Me.LocalResourceFile)

            For Each rTab As RadTab In ctlTabstrip.Tabs
                rTab.Text = Localization.GetString(rTab.Text & ".Tabname", LocalResourceFile)
            Next

            grdModules.MasterTableView.NoMasterRecordsText = Localization.GetString("NoModules", LocalResourceFile)
            For Each col As GridColumn In grdModules.Columns
                col.HeaderText = Localization.GetString(col.HeaderText & ".Header", LocalResourceFile)
            Next

        End Sub

        Private Sub AddAttributes(ByRef Node As RadTreeNode, ByVal objTab As TabInfo)

            Dim CanDelete As Boolean = True
            Dim CanHide As Boolean = True
            Dim CanMakeVisible As Boolean = True
            Dim CanEnable As Boolean = True
            Dim CanDisable As Boolean = True
            Dim CanMakeHome As Boolean = True

            If objTab Is Nothing Then
                Node.Attributes.Add("CanEdit", Boolean.FalseString)
                Node.Attributes.Add("CanView", Boolean.FalseString)
                Node.Attributes.Add("CanDelete", Boolean.FalseString)
                Node.Attributes.Add("CanHide", Boolean.FalseString)
                Node.Attributes.Add("CanMakeVisible", Boolean.FalseString)
                Node.Attributes.Add("CanEnable", Boolean.FalseString)
                Node.Attributes.Add("CanDisable", Boolean.FalseString)
                Node.Attributes.Add("CanMakeHome", Boolean.FalseString)
                Exit Sub
            End If

            If TabController.IsSpecialTab(objTab.TabID, PortalSettings) Or rblMode.SelectedValue = "H" Then
                CanDelete = False
                CanMakeHome = False
            End If

            If objTab.IsVisible Then
                CanMakeVisible = False
                CanHide = True
            Else
                CanMakeVisible = True
                CanHide = False
            End If

            If objTab.DisableLink Then
                CanDisable = False
                CanEnable = True
            Else
                CanDisable = True
                CanEnable = False
            End If

            Node.Attributes.Add("CanDelete", CanDelete.ToString)
            Node.Attributes.Add("CanHide", CanHide.ToString)
            Node.Attributes.Add("CanMakeVisible", CanMakeVisible.ToString)
            Node.Attributes.Add("CanEnable", CanEnable.ToString)
            Node.Attributes.Add("CanDisable", CanDisable.ToString)
            Node.Attributes.Add("CanMakeHome", CanMakeHome.ToString)

        End Sub

        Private Sub BindTree()

            ctlPages.Nodes.Clear()

            Dim rootNode As New RadTreeNode
            Dim strParent As String = "-1"

            If Not Settings("ParentPageFilter") Is Nothing Then
                strParent = Convert.ToString(Settings("ParentPageFilter"))
            End If

            If strParent = "-1" Then

                rootNode.Text = PortalSettings.PortalName
                rootNode.ImageUrl = IconPortal
                rootNode.Value = Null.NullInteger.ToString
                rootNode.Expanded = True
                'set to true as you must be able to create pages on the root
                rootNode.EnableContextMenu = True
                AddAttributes(rootNode, Nothing)

            Else
                Dim ctrl As New TabController
                Dim oParent As TabInfo = ctrl.GetTab(Convert.ToInt32(strParent), PortalId, False)
                If Not oParent Is Nothing Then
                    rootNode.Text = oParent.TabName
                    rootNode.ImageUrl = IconPortal
                    rootNode.Value = oParent.TabID.ToString
                    rootNode.Expanded = True
                    rootNode.EnableContextMenu = False
                    rootNode.PostBack = False
                End If
            End If


            For Each objTab As TabInfo In Tabs

                If strParent <> "-1" Then

                    If objTab.ParentId = Convert.ToInt32(strParent) Then

                        Dim node As New RadTreeNode
                        node.Text = objTab.TabName & " " & GetNodeStatusIcon(objTab)
                        node.Value = objTab.TabID.ToString
                        node.AllowEdit = True
                        node.ImageUrl = GetNodeIcon(objTab)
                        AddAttributes(node, objTab)

                        AddChildnodes(node)
                        rootNode.Nodes.Add(node)

                    End If

                Else

                    If objTab.Level = 0 Then

                        Dim node As New RadTreeNode
                        node.Text = objTab.TabName & " " & GetNodeStatusIcon(objTab)
                        node.Value = objTab.TabID.ToString
                        node.AllowEdit = True
                        node.ImageUrl = GetNodeIcon(objTab)
                        AddAttributes(node, objTab)

                        AddChildnodes(node)
                        rootNode.Nodes.Add(node)

                    End If

                End If

            Next

            ctlPages.Nodes.Add(rootNode)
            'AttachContextMenu(ctlPages)

            If Not Session("SelectedNode") Is Nothing Then

                Try
                    ctlPages.FindNodeByValue(Session("SelectedNode")).Selected = True
                    ctlPages.FindNodeByValue(Session("SelectedNode")).ExpandParentNodes()
                    Dim tabid As Integer = Convert.ToInt32(Session("SelectedNode"))
                    BindTab(tabid)
                    pnlDetails.Visible = True
                    pnlBulk.Visible = False
                    grdModules.Rebind()
                Catch
                End Try

            End If

        End Sub

        Private Sub AddChildnodes(ByVal ParentNode As RadTreeNode)

            ParentNode.Nodes.Clear()

            Dim parentid As Integer = Integer.Parse(ParentNode.Value)

            For Each objTab As TabInfo In Tabs
                If objTab.ParentId = parentid Then

                    Dim node As New RadTreeNode
                    node.Text = objTab.TabName & " " & GetNodeStatusIcon(objTab)
                    node.Value = objTab.TabID.ToString
                    node.AllowEdit = True
                    node.ImageUrl = GetNodeIcon(objTab)
                    AddAttributes(node, objTab)
                    'If objTab.HasChildren Then
                    '    node.ExpandMode = TreeNodeExpandMode.ServerSide
                    'End If

                    AddChildnodes(node)
                    ParentNode.Nodes.Add(node)

                End If
            Next

        End Sub

        Private Sub AttachContextMenu(ByRef Tree As RadTreeView)

            Dim menu As New RadTreeViewContextMenu
            menu.ID = "ctxt_PagesTree"

            Dim item As New RadMenuItem
            item.Text = Localization.GetString("ViewPage", Me.LocalResourceFile)
            item.Value = "view"
            item.ImageUrl = Me.IconView
            menu.Items.Add(item)

            item = New RadMenuItem
            item.Text = Localization.GetString("EditPage", Me.LocalResourceFile)
            item.Value = "edit"
            item.ImageUrl = Me.IconEdit
            menu.Items.Add(item)

            item = New RadMenuItem
            item.Text = Localization.GetString("DeletePage", Me.LocalResourceFile)
            item.Value = "delete"
            item.ImageUrl = Me.IconDelete
            menu.Items.Add(item)

            item = New RadMenuItem
            item.Text = Localization.GetString("MovePageUp", Me.LocalResourceFile)
            item.Value = "moveup"
            item.ImageUrl = Me.IconUp
            menu.Items.Add(item)

            item = New RadMenuItem
            item.Text = Localization.GetString("MovePageDown", Me.LocalResourceFile)
            item.Value = "movedown"
            item.ImageUrl = Me.IconDown
            menu.Items.Add(item)

            item = New RadMenuItem
            item.Text = Localization.GetString("AddPage", Me.LocalResourceFile)
            item.Value = "add"
            item.ImageUrl = Me.IconAdd
            menu.Items.Add(item)

            item = New RadMenuItem
            item.Text = Localization.GetString("UnHidePage", Me.LocalResourceFile)
            item.Value = "unhide"
            item.ImageUrl = Me.IconPageHidden
            menu.Items.Add(item)

            item = New RadMenuItem
            item.Text = Localization.GetString("DisablePage", Me.LocalResourceFile)
            item.Value = "disable"
            item.ImageUrl = Me.IconPageDisabled
            menu.Items.Add(item)

            ctlPages.ContextMenus.Add(menu)

        End Sub

        Private Function GetNodeStatusIcon(ByVal objTab As TabInfo) As String

            If objTab.DisableLink Then
                Return "<img src=""" & Me.IconPageDisabled & """ class=""statusicon"" />"
            End If

            If objTab.IsVisible = False Then
                Return "<img src=""" & Me.IconPageHidden & """ class=""statusicon"" />"
            End If

            Return ""

        End Function

        Private Function GetNodeIcon(ByVal objTab As TabInfo) As String

            If PortalSettings.HomeTabId = objTab.TabID Then
                Return IconHome
            End If

            If IsSecuredTab(objTab) Then

                If IsAdminTab(objTab) Then
                    Return Me.Icon_AdminOnly
                End If

                If IsRegisteredUserTab(objTab) Then
                    Return Me.Icon_RegisteredUsers
                End If

                Return Me.Icon_Secured

            End If

            Return Me.Icon_Everyone

        End Function

        Private Function IsSecuredTab(ByVal objTab As TabInfo) As Boolean

            Dim perms As TabPermissionCollection = objTab.TabPermissions
            For Each perm As TabPermissionInfo In perms
                If perm.RoleName = "All Users" AndAlso perm.AllowAccess Then
                    Return False
                End If
            Next

            Return True

        End Function

        Private Function IsRegisteredUserTab(ByVal objTab As TabInfo) As Boolean

            Dim perms As TabPermissionCollection = objTab.TabPermissions
            For Each perm As TabPermissionInfo In perms
                If perm.RoleName = PortalSettings.RegisteredRoleName AndAlso (perm.AllowAccess = True) Then
                    Return True
                End If
            Next

            Return False

        End Function

        Private Function IsAdminTab(ByVal objTab As TabInfo) As Boolean

            Dim perms As TabPermissionCollection = objTab.TabPermissions
            For Each perm As TabPermissionInfo In perms
                If perm.RoleName <> PortalSettings.AdministratorRoleName AndAlso (perm.AllowAccess = True) Then
                    Return False
                End If
            Next

            Return True

        End Function

        Private Sub PerformDragAndDrop(ByVal dropPosition As RadTreeViewDropPosition, ByVal sourceNode As RadTreeNode, ByVal destNode As RadTreeNode)

            Dim objTabController As New TabController
            Dim objSourceTab As TabInfo = objTabController.GetTab(Integer.Parse(sourceNode.Value), PortalId, True)
            Dim objTargetTab As TabInfo = objTabController.GetTab(Integer.Parse(destNode.Value), PortalId, True)

            Select Case dropPosition
                Case RadTreeViewDropPosition.Over
                    ' child
                    If Not sourceNode.IsAncestorOf(destNode) Then
                        sourceNode.Owner.Nodes.Remove(sourceNode)
                        destNode.Nodes.Add(sourceNode)
                        MoveTabToParent(objSourceTab, objTargetTab)
                    End If
                    Exit Select
                Case RadTreeViewDropPosition.Above
                    ' sibling - above
                    sourceNode.Owner.Nodes.Remove(sourceNode)
                    destNode.InsertBefore(sourceNode)
                    MoveTab(objSourceTab, objTargetTab, Position.Above)
                    Exit Select
                Case RadTreeViewDropPosition.Below
                    ' sibling - below
                    sourceNode.Owner.Nodes.Remove(sourceNode)
                    destNode.InsertAfter(sourceNode)
                    MoveTab(objSourceTab, objTargetTab, Position.Below)
                    Exit Select
            End Select

            DotNetNuke.Common.Utilities.DataCache.ClearTabsCache(PortalId)

        End Sub

        Private Sub MoveTabToParent(ByVal objTab As TabInfo, ByVal objTargetTab As TabInfo)

            Dim intLevelIncrement As Integer = 0

            If objTab.Level > (objTargetTab.Level + 1) Then
                intLevelIncrement = objTargetTab.Level - objTab.Level
            End If

            If objTab.Level < (objTargetTab.Level + 1) Then
                intLevelIncrement = objTargetTab.Level - objTab.Level
            End If

            Dim objTabController As New TabController

            'get current siblings of moving tab
            Dim siblingTabs As List(Of TabInfo) = GetSiblingTabs(objTab)
            Dim siblingCount As Integer = siblingTabs.Count

            'move all current siblings of moving tab one level up in order
            Dim tabIndex As Integer = GetIndexOfTab(objTab, siblingTabs)
            UpdateTabOrder(siblingTabs, tabIndex + 1, siblingCount - 1, -2)

            'get siblings of new position
            siblingTabs = objTabController.GetTabsByPortal(objTab.PortalID).DescendentsOf(objTargetTab.TabID)
            siblingCount = siblingTabs.Count

            'First make sure the list of siblings at the new position is sorted and spaced
            UpdateTabOrder(siblingTabs, objTab.CultureCode, objTab.PortalID, 2)

            Dim targetIndex As Integer = 0

            'We need to update the taborder for items that were after that position
            UpdateTabOrder(siblingTabs, targetIndex + 1, siblingCount - 1, 2)

            'Get the descendents of old tab position now before the new parentid is updated
            Dim descendantTabs As List(Of TabInfo) = objTabController.GetTabsByPortal(objTab.PortalID).DescendentsOf(objTab.TabID)

            'Update the current Tab to reflect new parent id and new taborder
            objTab.ParentId = objTargetTab.TabID


            objTab.TabOrder = 1
            objTabController.UpdateTab(objTab)

            'Update the moving tabs level and tabpath
            If objTab.Level < 0 Then objTab.Level = 0
            UpdateTabOrder(objTab, True)

            Dim blnLevelChanged As Boolean = (intLevelIncrement <> 0)
            If blnLevelChanged Then
                'Update the Descendents of the moving tab
                UpdateDescendantLevel(descendantTabs, intLevelIncrement)
            End If

        End Sub

        Private Sub MoveTab(ByVal objTab As TabInfo, ByVal objTargetTab As TabInfo, ByVal Position As Position)

            Dim intLevelIncrement As Integer = 0

            If objTab.Level > objTargetTab.Level Then
                intLevelIncrement = objTargetTab.Level - objTab.Level
            End If

            If objTab.Level < objTargetTab.Level Then
                intLevelIncrement = objTargetTab.Level - objTab.Level
            End If


            Dim objTabController As New TabController           

            ''get current siblings of moving tab
            Dim siblingTabs As List(Of TabInfo) = GetSiblingTabs(objTab)
            Dim siblingCount As Integer = siblingTabs.Count

            ''move all current siblings of moving tab one level up in order
            Dim tabIndex As Integer = GetIndexOfTab(objTab, siblingTabs)
            UpdateTabOrder(siblingTabs, tabIndex + 1, siblingCount - 1, -2)

            'get siblings of new position
            siblingTabs = GetSiblingTabs(objTargetTab)
            siblingCount = siblingTabs.Count

            'First make sure the list of siblings at the new position is sorted and spaced
            UpdateTabOrder(siblingTabs, objTab.CultureCode, objTab.PortalID, 2)

            'Find Index position of new positin in the Sibling List
            Dim targetIndex As Integer = GetIndexOfTab(objTargetTab, siblingTabs)

            Select Case Position
                Case Pages.Position.Above
                    targetIndex = targetIndex - 1
                Case Pages.Position.Below
                    targetIndex = targetIndex
            End Select

            'We need to update the taborder for items that were after that position
            UpdateTabOrder(siblingTabs, targetIndex + 1, siblingCount - 1, 2)

            'Get the descendents of old tab position now before the new parentid is updated
            Dim descendantTabs As List(Of TabInfo) = objTabController.GetTabsByPortal(objTab.PortalID).DescendentsOf(objTab.TabID)

            'Update the current Tab to reflect new parent id and new taborder
            objTab.ParentId = objTargetTab.ParentId

            Select Case Position
                Case Pages.Position.Above
                    objTab.TabOrder = objTargetTab.TabOrder - 2
                Case Pages.Position.Below
                    objTab.TabOrder = objTargetTab.TabOrder + 2
            End Select

            objTabController.UpdateTab(objTab)

            'Update the moving tabs level and tabpath
            If objTab.Level < 0 Then objTab.Level = 0
            UpdateTabOrder(objTab, True)

            Dim blnLevelChanged As Boolean = (intLevelIncrement <> 0)

            If blnLevelChanged Then
                'Update the Descendents of the moving tab
                UpdateDescendantLevel(descendantTabs, intLevelIncrement)
            End If            

        End Sub

#End Region

#Region "Public Methods"

        Public Function ModuleEditUrl(ByVal ModuleId As Integer) As String

            If IsNumeric(ModuleId) Then
                Dim ModuleController As New ModuleController
                Dim objModule As ModuleInfo = ModuleController.GetModule(ModuleId)
                If Not objModule Is Nothing Then
                    Return NavigateURL(objModule.TabID, "", "ctl=Module", "ModuleId=" & ModuleId.ToString)
                End If
            End If

            Return "#"

        End Function

        Public Function GetConfirmString() As String
            Return Localization.GetString("ConfirmDelete", LocalResourceFile)
        End Function

#End Region

#Region "Tab Moving Helpers"

        Private Sub UpdateDescendantLevel(ByVal descendantTabs As List(Of TabInfo), ByVal levelDelta As Integer)
            'Update the Descendents of this tab
            For Each descendent As TabInfo In descendantTabs
                descendent.Level = descendent.Level + levelDelta
                UpdateTabOrder(descendent, True)
            Next
        End Sub

        Private Sub UpdateTabOrderInternal(ByVal tabs As IEnumerable(Of TabInfo), ByVal increment As Integer)
            Dim tabOrder As Integer = 1
            For Each objTab As TabInfo In tabs.OrderBy(Function(t) t.TabOrder)
                If objTab.IsDeleted Then
                    objTab.TabOrder = -1
                    UpdateTabOrder(objTab, False)

                    'Update the tab order of all child languages
                    For Each localizedtab As TabInfo In objTab.LocalizedTabs.Values
                        localizedtab.TabOrder = -1
                        UpdateTabOrder(localizedtab, False)
                    Next
                Else
                    'Only update the tabOrder if it actually needs to be updated
                    If (objTab.TabOrder <> tabOrder) Then
                        objTab.TabOrder = tabOrder
                        UpdateTabOrder(objTab, False)

                        'Update the tab order of all child languages
                        For Each localizedtab As TabInfo In objTab.LocalizedTabs.Values
                            If localizedtab.TabOrder <> tabOrder Then
                                localizedtab.TabOrder = tabOrder
                                UpdateTabOrder(localizedtab, False)
                            End If
                        Next
                    End If

                    tabOrder += increment
                End If

            Next
        End Sub

        Private Sub UpdateTabOrder(ByVal tabs As List(Of TabInfo), ByVal culture As String, ByVal portalId As Integer, ByVal increment As Integer)
            Dim _PortalSettings As PortalSettings = PortalController.GetCurrentPortalSettings()
            If _PortalSettings IsNot Nothing AndAlso _PortalSettings.ContentLocalizationEnabled Then
                If String.IsNullOrEmpty(culture) Then
                    UpdateTabOrderInternal(tabs.Where(Function(t) t.CultureCode = _PortalSettings.DefaultLanguage OrElse String.IsNullOrEmpty(t.CultureCode)), increment)
                Else
                    UpdateTabOrderInternal(tabs, increment)
                End If
            Else
                UpdateTabOrderInternal(tabs, increment)
            End If
        End Sub

        Private Sub UpdateTabOrder(ByVal tabs As List(Of TabInfo), ByVal startIndex As Integer, ByVal endIndex As Integer, ByVal increment As Integer)
            For index As Integer = startIndex To endIndex
                Dim objTab As TabInfo = tabs(index)
                objTab.TabOrder += increment

                'UpdateOrder - Parent hasn't changed so we don't need to regenerate TabPath
                UpdateTabOrder(objTab, False)
            Next
        End Sub

        Private Sub UpdateTabOrder(ByVal objTab As TabInfo, ByVal updateTabPath As Boolean)

            If updateTabPath Then
                objTab.TabPath = GenerateTabPath(objTab.ParentId, objTab.TabName)
            End If

            DotNetNuke.Data.DataProvider.Instance().UpdateTabOrder(objTab.TabID, objTab.TabOrder, objTab.Level, objTab.ParentId, objTab.TabPath, UserController.GetCurrentUserInfo.UserID)
            DotNetNuke.Data.DataProvider.Instance().UpdateTabVersion(TabId, Guid.NewGuid())

            Dim objEventLog As New Services.Log.EventLog.EventLogController
            objEventLog.AddLog(objTab, PortalController.GetCurrentPortalSettings, UserController.GetCurrentUserInfo.UserID, "", Services.Log.EventLog.EventLogController.EventLogType.TAB_ORDER_UPDATED)

        End Sub

        Private Function GetSiblingTabs(ByVal objTab As TabInfo) As List(Of TabInfo)
            Dim objTabController As New TabController
            Return objTabController.GetTabsByPortal(objTab.PortalID).WithCulture(objTab.CultureCode, True).WithParentId(objTab.ParentId)
        End Function

        Private Function GetIndexOfTab(ByVal objTab As TabInfo, ByVal tabs As List(Of TabInfo)) As Integer
            Dim tabIndex As Integer = Null.NullInteger
            For index As Integer = 0 To tabs.Count - 1
                If tabs(index).TabID = objTab.TabID Then
                    tabIndex = index
                    Exit For
                End If
            Next
            Return tabIndex
        End Function

        Private Function GetParentTabId(ByVal lstTabs As List(Of TabInfo), ByVal CurrentIndex As Integer, ByVal ParentLevel As Integer) As Integer

            Dim oParent As TabInfo = lstTabs(0)

            For i As Integer = 0 To lstTabs.Count - 1
                If i = CurrentIndex Then
                    Return oParent.TabID
                Else
                    If lstTabs(i).Level = ParentLevel Then
                        oParent = lstTabs(i)
                    End If
                End If
            Next

        End Function

        Private Function CreateTabFromParent(ByVal objRoot As TabInfo, ByVal TabName As String, ByVal ParentId As Integer) As Integer

            Dim Tab As New TabInfo
            Tab.PortalID = PortalId
            Tab.TabName = TabName
            Tab.ParentId = ParentId


            Tab.Title = ""
            Tab.Description = ""
            Tab.KeyWords = ""
            Tab.IsVisible = objRoot.IsVisible
            Tab.DisableLink = objRoot.DisableLink

            Dim parentTab As TabInfo = Nothing
            Dim controller As New TabController()
            parentTab = controller.GetTab(ParentId, PortalId, False)

            If parentTab IsNot Nothing Then
                Tab.PortalID = parentTab.PortalID
                Tab.ParentId = parentTab.TabID
                Tab.Level = parentTab.Level + 1
            Else
                Return Null.NullInteger
            End If

            Tab.IconFile = ""
            Tab.IconFileLarge = ""
            Tab.IsDeleted = False
            Tab.Url = ""

            Tab.TabPermissions.Clear()
            If Tab.PortalID <> Null.NullInteger Then
                Tab.TabPermissions.AddRange(objRoot.TabPermissions)
            End If

            Tab.Terms.Clear()

            Tab.SkinSrc = objRoot.SkinSrc
            Tab.ContainerSrc = objRoot.ContainerSrc
            Tab.TabPath = GenerateTabPath(Tab.ParentId, Tab.TabName)

            'Check for invalid 
            If Regex.IsMatch(Tab.TabName, "^AUX$|^CON$|^LPT[1-9]$|^CON$|^COM[1-9]$|^NUL$|^SITEMAP$|^LINKCLICK$|^KEEPALIVE$|^DEFAULT$|^ERRORPAGE$", RegexOptions.IgnoreCase) Then
                Return Null.NullInteger
            End If

            'Set Culture Code
            Tab.CultureCode = objRoot.CultureCode


            'Validate Tab Path

            Dim tabID As Integer = TabController.GetTabByTabPath(Tab.PortalID, Tab.TabPath, Tab.CultureCode)

            If tabID <> Null.NullInteger Then
                Return Null.NullInteger
            End If

            Tab.StartDate = objRoot.StartDate
            Tab.EndDate = objRoot.EndDate
            Tab.RefreshInterval = objRoot.RefreshInterval

            Tab.SiteMapPriority = objRoot.SiteMapPriority
            Tab.PageHeadText = objRoot.PageHeadText
            Tab.IsSecure = objRoot.IsSecure
            Tab.PermanentRedirect = objRoot.PermanentRedirect

            Dim ctrl As New TabController
            Tab.TabID = ctrl.AddTab(Tab)

            Return Tab.TabID

        End Function

        Private Function CreateRootTab(ByVal TabName As String) As Integer

            Dim ctrl As New TabController
            Dim objRoot As TabInfo = ctrl.GetTab(PortalSettings.HomeTabId, PortalId, False)

            Dim Tab As New TabInfo
            Tab.PortalID = PortalId
            Tab.TabName = TabName
            Tab.ParentId = Null.NullInteger


            Tab.Title = ""
            Tab.Description = ""
            Tab.KeyWords = ""
            Tab.IsVisible = objRoot.IsVisible
            Tab.DisableLink = objRoot.DisableLink

            Tab.PortalID = PortalId
            Tab.ParentId = Null.NullInteger
            Tab.Level = 0

            Tab.IconFile = ""
            Tab.IconFileLarge = ""
            Tab.IsDeleted = False
            Tab.Url = ""

            Tab.TabPermissions.Clear()
            If Tab.PortalID <> Null.NullInteger Then
                Tab.TabPermissions.AddRange(objRoot.TabPermissions)
            End If

            Tab.Terms.Clear()

            Tab.SkinSrc = objRoot.SkinSrc
            Tab.ContainerSrc = objRoot.ContainerSrc
            Tab.TabPath = GenerateTabPath(Tab.ParentId, Tab.TabName)

            'Check for invalid 
            If Regex.IsMatch(Tab.TabName, "^AUX$|^CON$|^LPT[1-9]$|^CON$|^COM[1-9]$|^NUL$|^SITEMAP$|^LINKCLICK$|^KEEPALIVE$|^DEFAULT$|^ERRORPAGE$", RegexOptions.IgnoreCase) Then
                Return Null.NullInteger
            End If

            'Set Culture Code
            Tab.CultureCode = objRoot.CultureCode


            'Validate Tab Path

            Dim tabID As Integer = TabController.GetTabByTabPath(Tab.PortalID, Tab.TabPath, Tab.CultureCode)

            If tabID <> Null.NullInteger Then
                Return Null.NullInteger
            End If

            Tab.StartDate = objRoot.StartDate
            Tab.EndDate = objRoot.EndDate
            Tab.RefreshInterval = objRoot.RefreshInterval

            Tab.SiteMapPriority = objRoot.SiteMapPriority
            Tab.PageHeadText = objRoot.PageHeadText
            Tab.IsSecure = objRoot.IsSecure
            Tab.PermanentRedirect = objRoot.PermanentRedirect

            Tab.TabID = ctrl.AddTab(Tab)

            Return Tab.TabID

        End Function

#End Region

    End Class

End Namespace

